const http = require('http');
const https = require('https');
const cors = require('cors');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
exports.router = (app) => {
  // 临时解决请求会发送cookie的问题，后面去掉
  app.use((_req, res, next) => {
    res.setHeader('Access-Control-Request-Private-Network', 'true');
    res.setHeader('Access-Control-Allow-Private-Network', 'true');
    next();
  });
  app.use(cors());
  app.use((req, res, next) => {
    if (req.url == '/https.html') {
      fs.createReadStream(path.resolve(__dirname, '../scripts/https.html')).pipe(res);
    } else {
      next();
    }
  });
  app.get('/_consoleMsg', (req, res) => {
    const msg = req.query.msg;
    global._webpackConsole = JSON.parse(msg)
    res.send('ok');
  });
}

exports.sendMsg = ({port, isHttps, msg}) => {
  if (isHttps) {
    https.get(`https://127.0.0.1:${port}/_consoleMsg?msg=` + JSON.stringify(msg)).on('error', (e) => {});
  } else {
    http.get(`http://127.0.0.1:${port}/_consoleMsg?msg=` + JSON.stringify(msg)).on('error', (e) => {});
  }
}